class ApiResponse<T> {
  final bool success;
  final String? message;
  final T? data;
  final int? code;
  final String? error;

  ApiResponse({
    required this.success,
    this.message,
    this.data,
    this.code,
    this.error,
  });

  factory ApiResponse.success({T? data, String? message, int? code}) {
    return ApiResponse<T>(
      success: true,
      data: data,
      message: message,
      code: code,
    );
  }

  factory ApiResponse.error({String? message, String? error, int? code}) {
    return ApiResponse<T>(
      success: false,
      message: message,
      error: error,
      code: code,
    );
  }

  factory ApiResponse.fromJson(
    Map<String, dynamic> json,
    T Function(Map<String, dynamic>)? fromJson,
  ) {
    final success = json['success'] ?? json['code'] == 200;
    final message = json['message'];
    final code = json['code'];
    final error = json['error'];

    T? data;
    if (json['data'] != null && fromJson != null) {
      try {
        data = fromJson(json['data']);
      } catch (e) {
        print('Error parsing data: $e');
      }
    }

    return ApiResponse<T>(
      success: success,
      message: message,
      data: data,
      code: code,
      error: error,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'success': success,
      'message': message,
      'data': data,
      'code': code,
      'error': error,
    };
  }

  @override
  String toString() {
    return 'ApiResponse{success: $success, message: $message, data: $data, code: $code, error: $error}';
  }
}

// 分页响应模型
class PaginatedResponse<T> {
  final List<T> data;
  final int currentPage;
  final int totalPages;
  final int totalItems;
  final int itemsPerPage;
  final bool hasNext;
  final bool hasPrevious;

  PaginatedResponse({
    required this.data,
    required this.currentPage,
    required this.totalPages,
    required this.totalItems,
    required this.itemsPerPage,
    required this.hasNext,
    required this.hasPrevious,
  });

  factory PaginatedResponse.fromJson(
    Map<String, dynamic> json,
    T Function(Map<String, dynamic>) fromJson,
  ) {
    final List<dynamic> dataList = json['data'] ?? [];
    final data = dataList.map((item) => fromJson(item)).toList();

    return PaginatedResponse<T>(
      data: data,
      currentPage: json['current_page'] ?? 1,
      totalPages: json['total_pages'] ?? 1,
      totalItems: json['total_items'] ?? 0,
      itemsPerPage: json['items_per_page'] ?? 10,
      hasNext: json['has_next'] ?? false,
      hasPrevious: json['has_previous'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'data': data,
      'current_page': currentPage,
      'total_pages': totalPages,
      'total_items': totalItems,
      'items_per_page': itemsPerPage,
      'has_next': hasNext,
      'has_previous': hasPrevious,
    };
  }
}

// 通用数据模型
class UserProfile {
  final String id;
  final String username;
  final String? email;
  final String? avatar;
  final String? stage;
  final String? grade;
  final List<String> subjects;
  final String? learningGoal;
  final DateTime? createdAt;
  final DateTime? updatedAt;

  UserProfile({
    required this.id,
    required this.username,
    this.email,
    this.avatar,
    this.stage,
    this.grade,
    this.subjects = const [],
    this.learningGoal,
    this.createdAt,
    this.updatedAt,
  });

  factory UserProfile.fromJson(Map<String, dynamic> json) {
    return UserProfile(
      id: json['id'],
      username: json['username'],
      email: json['email'],
      avatar: json['avatar'],
      stage: json['stage'],
      grade: json['grade'],
      subjects: List<String>.from(json['subjects'] ?? []),
      learningGoal: json['learning_goal'],
      createdAt:
          json['created_at'] != null
              ? DateTime.parse(json['created_at'])
              : null,
      updatedAt:
          json['updated_at'] != null
              ? DateTime.parse(json['updated_at'])
              : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'username': username,
      'email': email,
      'avatar': avatar,
      'stage': stage,
      'grade': grade,
      'subjects': subjects,
      'learning_goal': learningGoal,
      'created_at': createdAt?.toIso8601String(),
      'updated_at': updatedAt?.toIso8601String(),
    };
  }
}

class LearningStats {
  final int totalStudyTime; // 总学习时长（分钟）
  final int totalQuestions; // 总题目数
  final int correctAnswers; // 正确答题数
  final double accuracy; // 正确率
  final Map<String, double> subjectMastery; // 各科目掌握度
  final int continuousDays; // 连续学习天数
  final DateTime lastStudyDate; // 最后学习日期

  LearningStats({
    required this.totalStudyTime,
    required this.totalQuestions,
    required this.correctAnswers,
    required this.accuracy,
    required this.subjectMastery,
    required this.continuousDays,
    required this.lastStudyDate,
  });

  factory LearningStats.fromJson(Map<String, dynamic> json) {
    return LearningStats(
      totalStudyTime: json['total_study_time'] ?? 0,
      totalQuestions: json['total_questions'] ?? 0,
      correctAnswers: json['correct_answers'] ?? 0,
      accuracy: (json['accuracy'] ?? 0.0).toDouble(),
      subjectMastery: Map<String, double>.from(json['subject_mastery'] ?? {}),
      continuousDays: json['continuous_days'] ?? 0,
      lastStudyDate: DateTime.parse(json['last_study_date']),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'total_study_time': totalStudyTime,
      'total_questions': totalQuestions,
      'correct_answers': correctAnswers,
      'accuracy': accuracy,
      'subject_mastery': subjectMastery,
      'continuous_days': continuousDays,
      'last_study_date': lastStudyDate.toIso8601String(),
    };
  }
}
